<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <h2>车辆信息：</h2>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="品牌">
              <a-input
                placeholder="请输入品牌"
                disabled
                v-decorator="['brand', { rules: [{ required: true, message: '请输入品牌' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="品牌车型">
              <a-input
                placeholder="请输入品牌车型"
                disabled
                v-decorator="['brandModel', { rules: [{ required: true, message: '请输入品牌车型' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车架号VIN码">
              <a-input
                placeholder="请输入车架号VIN码"
                disabled
                v-decorator="['vin', { rules: [{ required: true, message: '请输入车架号VIN码' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <h2>接收方信息：</h2>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="接收方姓名">
              <a-input
                placeholder="请输入接收方姓名"
                v-decorator="['receiverName', { rules: [{ required: true, message: '请输入接收方姓名' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="接收方电话">
              <a-input
                placeholder="请输入接收方电话"
                v-decorator="['receiverPhone', { rules: [{ required: true, message: '请输入接收方电话' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="证件类型">
              <!-- <a-input
                placeholder="请输入证件类型"
                v-decorator="['receiverCertType', { rules: [{ required: true, message: '请输入证件类型' }] }]"
              />-->
              <a-select
                placeholder="请选择证件类型"
                v-decorator="['receiverCertType', { rules: [{ required: true, message: '请输入证件类型' }] }]"
              >
                <a-select-option value>请选择</a-select-option>
                <a-select-option value="1">身份证</a-select-option>
                <a-select-option value="2">护照</a-select-option>
                <a-select-option value="3">士官证</a-select-option>
                <a-select-option value="4">居住证</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="证件号">
              <a-input
                placeholder="请输入证件号"
                v-decorator="['receiverCertNo', { rules: [{ required: true, message: '请输入证件号' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="交付时间">
              <a-input
                placeholder="请输入交付时间"
                v-decorator="['deliverTime', { rules: [{ required: true, message: '请输入交付时间' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="交付地点">
              <a-input
                placeholder="请输入交付地点"
                v-decorator="['deliveryAddr', { rules: [{ required: true, message: '请输入交付地点' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <h2>交付方信息：</h2>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="交付方姓名">
              <!-- <a-input
                placeholder="请输入交付方姓名"
                @blur="nameBlur"
                autocomplete="off"
                v-decorator="['name', {
                  rules: [
                    { required: true, message: '请输入交付方姓名' },
                    {
                      validator: (rule, value, callback) => {
                        if (value && value.trim() == '') {
                          callback('请输入交付方姓名')
                        }
                        callback();
                      }
                    }
                  ]
                }]"
              /> -->
              <a-auto-complete
                v-decorator="['name', { rules: [{ required: true, message: '请输入交付方姓名' }] }]"
                placeholder="请输入交付方姓名"
                :data-source="nameData"
                @select="nameSelect"
                @change="nameChange"
              ></a-auto-complete>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="交付方电话">
              <a-input
                placeholder="请输入交付方电话"
                v-decorator="['phone', { rules: [{ required: true, message: '请输入交付方电话' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <h2>交付清单：</h2>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="24">
            <a-checkbox-group @change="onChange" style="width: 100%;" v-model="shouxuList">
              <a-row>
                <a-col :span="6" v-for="(value,key) in shouxuList" :key="key">
                  <a-checkbox :value="value" disabled>{{ value }}</a-checkbox>
                </a-col>
              </a-row>
            </a-checkbox-group>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="24">
            <a-checkbox-group @change="onChange2" style="width: 100%;" v-model="zhuangbeiList">
              <a-row>
                <a-col :span="6" v-for="(value,key) in zhuangbeiList" :key="key">
                  <a-checkbox :value="value" disabled>{{ value }}</a-checkbox>
                </a-col>
              </a-row>
            </a-checkbox-group>
          </a-col>
        </a-row>
        <!--  <a-row>
          <h2>上传附件：</h2>
        </a-row>
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图片">
              <a-upload
                name="appearanceImg"
                enctype="multipart/form-data"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :action="importImgAction"
                :headers="headers"
                :data="picData"
                :before-upload="beforeUpload"
                @change="handleChange"
                v-decorator="['accessoriesContents', { rules: [{ required: true, message: '请添加图片' }] }]"
              >
                <img v-if="imageUrl" :src="imageUrl" alt="file" />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传照片</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            3
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图片">
              <a-upload
                name="accessoriesContents"
                enctype="multipart/form-data"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :action="importImgAction"
                :headers="headers"
                :data="picData"
                :before-upload="beforeUpload"
                @change="handleChange2"
                v-decorator="['accessoriesContents', {}]"
              >
                <img v-if="imageUrl2" :src="imageUrl2" alt="file" />
                <div v-else>
                  <a-icon :type="loading2 ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传照片</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>-->
      </a-form>
    </a-spin>
    <!-- <a-button
      type="primary"
      @click="saveDraft"
      style="position: relative;left: 50%;transform: translateX(-50%);"
    >预览打印</a-button>-->
  </j-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import axios from 'axios'
import qs from 'qs'
export default {
  name: 'SendOutModel',
  data() {
    return {
      title: '交易信息',
      visible: false,
      model: {},
      saleSource: [],
      SaleInfosLike: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      loading: '',
      loading2: '',
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {},
      url: {
        add: '/sale/cxmSaleDeliverInfo/addDeliverInfo',
        edit: '/sale/cxmSaleDeliverInfo/addDeliverInfo',
        imgAction: 'cxm/cxmCommonBusiness/uploadPlainText',
        getAcc: '/sale/cxmSaleStaffInfo/getAccount',
        brandList: '/sale/cxmSaleBaseInfo/queryByTypes',
        queryStaffFuzzy: '/sale/cxmSaleStaffInfo/queryStaffFuzzy',
        getCheckList: '/sale/cxmSaleCarInfo/queryCarInfoByVin'
      },
      deliveryStaffId: '',//交付专员的id
      phone: '',//交付专员的手机号
      showDing: false,
      showEnterpriseUscc: false,
      imageUrl: '',
      imageUrl2: '',
      headers: {},
      picData: {},
      shouxuList: [],
      zhuangbeiList: [],
      nameData:[]
      /* appearanceImg: "",
      qrCodeImg: "",
      nameplateImg: "",
      certificateImg: "", */
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = { "X-Access-Token": token, "Content-Type": "application/x-www-form-urlencoded" }
/*     getAction(this.url.brandList + "?dataTypes=6,7").then((res) => {
      if (res.success) {
        for (let i = 0; i < res.result['6'].length; i++) {
          this.shouxuList.push(res.result['6'][i].name)
        }
        for (let i = 0; i < res.result['7'].length; i++) {
          this.zhuangbeiList.push(res.result['7'][i].name)
        }
        console.log(res.result['6']);
        console.log(res.result['7']);
      }
    }) */
  },
  computed: {
    importImgAction: function () {
      return `${process.env.VUE_APP_BASE_API}${this.url.imgAction}`
    }
  },
  methods: {
    changeDepositNotes(val) {
      if (val == '不可退') {
        this.showDing = true
      } else {
        this.showDing = false
      }
    },
    add() {
      const that = this;
      that.edit({})
    },
    edit(record) {
      console.log(record);
      this.form.resetFields()
      this.model = Object.assign({}, record)
      console.log(this.model);
      getAction(this.url.getCheckList, { vin: this.model.vin }).then((res) => {
        console.log(res);
        if (res.success) {
          if (res.result.accessoriesId) this.shouxuList = res.result.accessoriesId.split(",")
          if (res.result.originalEquipmentId) this.zhuangbeiList = res.result.originalEquipmentId.split(",")
        }
        console.log(this.shouxuList, this.zhuangbeiList);
      })
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue({
          brand: this.model.brand,
          brandModel: this.model.brandModel,
          vin: this.model.vin,
          receiverName: this.model.receiverName,
          receiverPhone: this.model.receiverName,
          receiverCertType: this.model.receiverCertType,
          receiverCertNo: this.model.receiverCertNo,
          deliverTime: this.model.receiverCertNo ? moment(this.model.receiverCertNo) : null,
          deliveryAddr: this.model.deliveryAddr,
        })
      })
    },
    getBase64(img, callback) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('您只能上传jpg或png格式的文件');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB');
      }
      return isJpgOrPng && isLt2M;
    },
    close() {
      this.$emit('close')
      this.zhuangbeiList = [];
      this.shouxuList = [];
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        console.log(this);
        if (!err) {
          that.confirmLoading = true
          let httpurl = this.url.edit
          let method = 'post'
          let formData = Object.assign(this.model, values)
          //时间格式化
          formData.deliveryStaffId = this.deliveryStaffId
          formData.phone = this.phone;
          /* formData.shouxuList = this.checkboxgroupvalue;
          formData.zhuangbeiList = this.checkboxgroupvalue2; */
          formData.deliverContents = this.shouxuList.concat(this.zhuangbeiList).join(",")
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    nameSelect(value) {
      let params = { name: `*${value}*` };
      getAction(this.url.queryStaffFuzzy, params).then((res) => {
        console.log(res);
        if (res.success) {
          this.deliveryStaffId = null;
          this.phone = null;
          if (res.result[0]) {
            this.deliveryStaffId = res.result[0].id;
            this.phone = res.result[0].phone
          }
          console.log(this.deliveryStaffId);
          console.log(this.phone);
          this.$nextTick(() => {
            this.form.setFieldsValue({
              phone: this.phone
            })
          })
        }
      })
    },
    nameChange(value){
      let params = { name: `*${value}*` };
      this.nameData = [];
      getAction(this.url.queryStaffFuzzy, params).then((res)=>{
        if (res.success){
          for (let i = 0; i < res.result.length; i++) {
            this.nameData.push(res.result[i].name)
          }
        }
      })
    },
    handleCancel() {
      this.close()
    },
    onChange(checkedValues) {
      console.log('checked = ', checkedValues);
      console.log('value = ', this.value);
    },
    onChange2(checkedValues) {
      console.log('checked = ', checkedValues);
      console.log('value = ', this.value);
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('您只能上传jpg或png格式的文件');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB');
      }
      return isJpgOrPng && isLt2M;
    },
    handleChange(info) {
      console.log(info);
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl;
          this.loading = false;
          let params = {
            "content": imageUrl,
            "name": info.file.name,
            "encodeType": 'base64'
          }
          axios.post(this.importImgAction, qs.stringify(params), {
            headers: this.headers
          }).then((res) => {
            if (res.data.success) {
              console.log(res.data.result);
              this.appearanceImg = res.data.result
            }
          })
        });
      }
    },
    handleChange2(info) {
      console.log(info);
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl2 = imageUrl;
          this.loading2 = false;
          let params = {
            "content": imageUrl,
            "name": info.file.name,
            "encodeType": 'base64'
          }
          axios.post(this.importImgAction, qs.stringify(params), {
            headers: this.headers
          }).then((res) => {
            if (res.data.success) {
              console.log(res.data.result);
              this.appearanceImg = res.data.result
            }
          })
        });
      }
    },
  },
  computed: {
    importImgAction: function () {
      return `${process.env.VUE_APP_BASE_API}${this.url.imgAction}`
    }
  },
}
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-upload-select-picture-card img {
  width: 128px;
  height: 128px;
}
</style>